package com.lbd.system.service.impl;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.system.bean.Dictionary;
import com.lbd.system.dao.DictionaryRepository;
import com.lbd.system.service.DictionaryService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WangYajie on 2016/9/19.
 */
@Service
@Transactional
public class DictionaryServiceImpl extends BaseServiceImpl<Dictionary, DictionaryRepository> implements DictionaryService {

    @Autowired
    DictionaryRepository repository;

    @Override
    public String buildJpql(Dictionary dictionary, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder(" from  Dictionary t order by id ");
        return jpqlBuilder.toString();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Dictionary> findDictionaryAllKeys() {

        List<Dictionary> resultList = em.createQuery(" from Dictionary where parent is null").getResultList();
        setParentNull(resultList);
//        return em.createQuery(" from Dictionary where LENGTH(parentId)=0 or parentId is null").getResultList();
        return resultList;
    }

    private void setParentNull(List<Dictionary> resultList) {
        if (CollectionUtils.isEmpty(resultList)) {
            return;
        }
        for (Dictionary menu : resultList) {
            setParentNull(menu.getItems());
            menu.setParent(null);
        }

    }

    @Override
    public List<Dictionary> findDictionaryContent(String key) {
        Dictionary dictionary = repository.findDictionaryByCode(key);
        if (dictionary == null) {
            return Collections.emptyList();
        }
        return repository.findDictionaryByParent(dictionary);
    }

    @Override
    public Dictionary findById(String id) {
        return repository.findOne(id);
    }

    @Override
    public Map<String, Map<String, String>> getDictionary(String key) {
        String[] keys = key.split(",");
        Map<String, Map<String, String>> map = new HashMap<>();
        Map<String, String> subMap;
        List<Dictionary> dictionaryList = repository.findDictionaryByCodeIn(keys);
        for (Dictionary dic : dictionaryList) {
            List<Dictionary> subDicList = repository.findDictionaryByParent(dic);
            subMap = new HashMap<>();
            for (Dictionary dictionary : subDicList) {
                subMap.put(dictionary.getCode().toString(), dictionary.getName());
            }
            map.put(dic.getCode().toString(), subMap);
        }
        return map;
    }
}
